﻿package rob.core{
	import flash.display.Sprite;
	import rob.data.Vect3d;
	import rob.maths.VectorMaths;
	
	// the base of a building, for: 
	// * collision detection
	// * sprite-on-building ordering
	public class Base3d extends Sprite{
		private var _aVertex:Array;
		private var _aPolygon:Array;
		private var _aNormals:Array;
		
		public function Base3d(aBaseVertex:Array,aBasePolygon:Array):void{
			_aVertex = aBaseVertex;
			_aPolygon = aBasePolygon;
			_aNormals = [];
			_computeNormals();
			visible = false;
		}

		private function _computeNormals():void{
			// first use first 3 points (in order) to determine
			// if aBaseVertex order is clockwise or anticlockwise
			// (i think it's possible order can be clockwise... maybe not)
			var vs:Array = _aVertex, v0:Vect3d, v1:Vect3d, cp:Vect3d, sign:Number;
				v0 = VectorMaths.sub(vs[1],vs[0]);
				v1 = VectorMaths.sub(vs[2],vs[1]);
				cp = VectorMaths.cp(v0,v1);
				sign = (cp.y > 0) ? 1 : -1;
			// construct normals, if anti-clockwise dir then rotate clockwise pi/2
			// correct order if clockwise using sign
			var l:uint = vs.length;
			for(var i:uint in vs){
				v0 = VectorMaths.sub(vs[(i+1)%l],vs[i]);
				VectorMaths.rotateBy(-sign*Math.PI/2,v0);
				VectorMaths.normalise(v0);
				_aNormals[i] = v0;
			}
		}
		
		// draw base
		public function draw():void{
			with(this.graphics){
				//lineStyle(0,0xFF0000);
				beginFill(0,1);
				moveTo(_aVertex[0].sx,_aVertex[0].sy);
				for each(var p in _aVertex){
					lineTo(p.sx,p.sy);
				}
				endFill();
			}
		}
		
		public function get aVertex():Array{ return _aVertex; }
		public function get aPolygon():Array{ return _aPolygon; }
		public function get aNormals():Array{ return _aNormals; }
		
	}
}